package com.fbt.transfer.app.driver.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.fbt.transfer.app.driver.socket.SocketManager;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.util.PermissionManager;
import com.fbt.transfer.app.driver.util.UserManager;
import java.util.Optional;

public class FloatingWindowService extends Service {
    private static final String CHANNEL_ID = "FloatingWindowService";
    private static final int NOTIFICATION_ID = 1;
    private static final String TAG = "FloatingWindowService";
    
    private WindowManager windowManager = null;
    private View floatingView = null;
    private WindowManager.LayoutParams params = null;
    private float initialX, initialY;
    private int initialTouchX, initialTouchY;
    private boolean isDragging = false;
    private SocketManager socketManager = null;
    private long lastClickTime = 0;
    // 点击延迟时间（毫秒）
    private static final long CLICK_DELAY = 300;
    private Handler mainHandler = null;
    private int screenWidth;
    private int screenHeight;
    private int statusBarHeight;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service onCreate");
        
        try {
            // 立即创建通知渠道和通知
            createNotificationChannel();
            Notification notification = createNotification();
            
            // 立即启动前台服务
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForeground(NOTIFICATION_ID, notification);
                Log.d(TAG, "Foreground service started");
            }
            
            // 初始化Handler
            mainHandler = new Handler(Looper.getMainLooper());
            
            // 延迟检查其他条件
            mainHandler.postDelayed(() -> {
                try {
                    // 检查用户是否已登录
                    if (!UserManager.getInstance(this).isLoggedIn()) {
                        Log.d(TAG, "User is not logged in, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 检查悬浮窗是否启用
                    if (!UserManager.getInstance(this).isFloatingWindowEnabled()) {
                        Log.d(TAG, "Floating window is disabled, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 检查是否有悬浮窗权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(this)) {
                            Log.e(TAG, "No overlay permission, stopping service");
                            stopSelf();
                            return;
                        }
                    }
                    
                    // 检查应用是否在后台
                    if (!SocketManager.getInstance(this).isBackground()) {
                        Log.d(TAG, "App is in foreground, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 初始化其他组件
                    initializeServiceComponents();
                } catch (Exception e) {
                    Log.e(TAG, "Error in onCreate post: " + e.getMessage());
                    stopSelf();
                }
            }, 100); // 从1000ms减少到100ms
        } catch (Exception e) {
            Log.e(TAG, "Error in onCreate: " + e.getMessage());
            stopSelf();
        }
    }

    private void initializeServiceComponents() {
        // 获取屏幕尺寸
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        
        // 获取状态栏高度
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        
        socketManager = SocketManager.getInstance(this);
        
        // 安全移除已存在的悬浮窗
        removeFloatingWindow();
        
        // 创建新的悬浮窗
        createFloatingWindow();
        
        // Set connection state listener
        socketManager.setConnectionStateListener(isConnected -> 
                                                     Optional.ofNullable(floatingView).ifPresent(view -> {
            TextView statusText = view.findViewById(R.id.tv_status_text);
            statusText.setText(isConnected ? "东潮在线" : "东潮离线");
            ImageView statusIcon = view.findViewById(R.id.iv_status);
            statusIcon.setSelected(isConnected);
        }));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service onStartCommand");
        
        try {
            // 确保服务启动时立即设置前台通知
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Notification notification = createNotification();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
                } else {
                    startForeground(NOTIFICATION_ID, notification);
                }
                Log.d(TAG, "Foreground service started in onStartCommand");
            }
            
            // 延迟检查其他条件
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                try {
                    // 检查用户是否已登录
                    if (!UserManager.getInstance(this).isLoggedIn()) {
                        Log.d(TAG, "User is not logged in, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 检查悬浮窗是否启用
                    if (!UserManager.getInstance(this).isFloatingWindowEnabled()) {
                        Log.d(TAG, "Floating window is disabled, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 检查是否有悬浮窗权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(this)) {
                            Log.e(TAG, "No overlay permission, stopping service");
                            stopSelf();
                            return;
                        }
                    }
                    
                    // 检查应用是否在后台
                    if (!SocketManager.getInstance(this).isBackground()) {
                        Log.d(TAG, "App is in foreground, stopping service");
                        stopSelf();
                        return;
                    }
                    
                    // 初始化服务组件
                    initializeServiceComponents();
                } catch (Exception e) {
                    Log.e(TAG, "Error in service initialization: " + e.getMessage());
                    stopSelf();
                }
            }, 100); // 从1000ms减少到100ms
            
        } catch (Exception e) {
            Log.e(TAG, "Error in onStartCommand: " + e.getMessage());
            stopSelf();
        }
        
        return START_NOT_STICKY;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "悬浮窗服务",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("用于显示悬浮窗服务的通知");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
            Log.d(TAG, "Notification channel created");
        }
    }

    private Notification createNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("正在听单")
            .setContentText("东潮调度后台运行")
            .setSmallIcon(R.drawable.ic_listening)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(true); // 设置为持续通知

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
        }

        return builder.build();
    }

    private void removeFloatingWindow() {
        if (floatingView != null && windowManager != null) {
            try {
                // 检查视图是否已经附加到窗口
                if (floatingView.getParent() != null) {
                    windowManager.removeView(floatingView);
                    Log.d(TAG, "Floating window removed successfully");
                } else {
                    Log.d(TAG, "Floating window already removed");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error removing floating window: " + e.getMessage());
            } finally {
                floatingView = null;
            }
        }
    }

    private void createFloatingWindow() {
        Log.d(TAG, "Creating floating window");
        // 再次检查悬浮窗是否启用
        if (!UserManager.getInstance(this).isFloatingWindowEnabled()) {
            Log.d(TAG, "Floating window is disabled, not creating window");
            stopSelf();
            return;
        }

        if (!PermissionManager.getInstance(this).hasOverlayPermission(this)) {
            Log.e(TAG, "没有悬浮窗权限，无法创建悬浮窗");
            stopSelf();
            return;
        }

        // 安全移除已存在的悬浮窗
        removeFloatingWindow();

        params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                : WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 0;
        params.y = 200; // 距离顶部的距离

        try {
            floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_window, null);
            Log.d(TAG, "Floating window layout inflated successfully");
            
            // 获取悬浮窗视图的尺寸
            floatingView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            final int windowWidth = floatingView.getMeasuredWidth();
            final int windowHeight = floatingView.getMeasuredHeight();
            
            floatingView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            initialX = params.x;
                            initialY = params.y;
                            initialTouchX = (int) event.getRawX();
                            initialTouchY = (int) event.getRawY();
                            isDragging = false;
                            lastClickTime = System.currentTimeMillis();
                            return true;
                        case MotionEvent.ACTION_MOVE:
                            int currentX = (int) event.getRawX();
                            int currentY = (int) event.getRawY();
                            int deltaX = currentX - initialTouchX;
                            int deltaY = currentY - initialTouchY;
                            
                            if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                isDragging = true;
                            }
                            
                            // 计算新位置
                            int newX = (int) (initialX + deltaX);
                            int newY = (int) (initialY + deltaY);
                            
                            // 边界检查
                            newX = Math.max(0, Math.min(newX, screenWidth - windowWidth));
                            newY = Math.max(statusBarHeight, Math.min(newY, screenHeight - windowHeight));
                            
                            params.x = newX;
                            params.y = newY;
                            windowManager.updateViewLayout(floatingView, params);
                            return true;
                        case MotionEvent.ACTION_UP:
                            if (!isDragging && System.currentTimeMillis() - lastClickTime < CLICK_DELAY) {
                                // 点击事件，打开应用
                                Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                            return true;
                    }
                    return false;
                }
            });

            windowManager.addView(floatingView, params);
            Log.d(TAG, "Floating window added successfully");
        } catch (Exception e) {
            Log.e(TAG, "Error creating floating window: " + e.getMessage());
            removeFloatingWindow();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service onDestroy");
        try {
            // 停止前台服务
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                stopForeground(true);
            }
            // 移除悬浮窗
            removeFloatingWindow();
            // 清理资源
            if (mainHandler != null) {
                mainHandler.removeCallbacksAndMessages(null);
            }
            if (socketManager != null) {
                socketManager.setConnectionStateListener(null);
            }
            Log.d(TAG, "Service resources cleaned up");
        } catch (Exception e) {
            Log.e(TAG, "Error in onDestroy: " + e.getMessage());
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
